import { userApi } from "@/api/user.ts";

interface Cache<T> {
  data: T | null;
  timestamp: number;
  isFetching: boolean;
  pendingCallbacks: Array<(data: T) => void>;
}

const CACHE_EXPIRY = 5 * 60 * 1000; // 5分钟缓存

// 初始化泛型缓存对象
let cache: Cache<any> = {
  data: null,
  timestamp: 0,
  isFetching: false,
  pendingCallbacks: [],
};

/**
 * 获取用户信息
 * @param forceRefresh 是否强制刷新缓存
 * @returns Promise<UserInfo>
 */
export const getUserInfo = async <T>(
  forceRefresh: boolean = false,
): Promise<T> => {
  // 检查有效缓存
  if (
    !forceRefresh &&
    cache.data &&
    Date.now() - cache.timestamp < CACHE_EXPIRY
  ) {
    return cache.data as T;
  }

  // 处理并发请求
  if (cache.isFetching) {
    return new Promise<T>((resolve) => {
      cache.pendingCallbacks.push(resolve as (data: any) => void);
    });
  }

  // 设置获取状态
  cache.isFetching = true;

  try {
    const res = await userApi.getBloggerInfo();

    // 更新缓存
    cache.data = res;
    cache.timestamp = Date.now();

    // 执行所有等待的回调
    cache.pendingCallbacks.forEach((callback) => callback(res));
    cache.pendingCallbacks = [];

    return res as T;
  } catch (error: unknown) {
    // 失败时返回过期缓存作为降级方案
    if (cache.data) {
      console.warn("Using stale cache due to API error:", error);
      return cache.data as T;
    }
    throw error;
  } finally {
    cache.isFetching = false;
  }
};
